package com.getsendsocial.GetSendSocial.Database;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;

import com.getsendsocial.GetSendSocial.R;
import com.getsendsocial.GetSendSocial.Activity.ContactActivity;

public class GetContact extends AsyncTask<ContentResolver, Void, ContactAdapter> {


	private ArrayList<String> contacts = new ArrayList<String>();
	private Context ctx;
	private ArrayList<String> lst;
	private boolean flg;
	private ContactAdapter adp;


	public GetContact(Context c,boolean flag, ArrayList<String> list){
		lst = new ArrayList<String>();
		ctx=c;
		flg = flag;
		if (flag == true){
			for (int i = 0; i<list.size(); i++)
				lst.add(list.get(i));
		}
	}


	@Override
	protected ContactAdapter doInBackground(ContentResolver... arg0) {

		if(flg==false){
			ArrayList<String> temp = new ArrayList<String>();
			temp.add("Inserisci destinatario:");

			init();
			String[] prj = {Phone.DISPLAY_NAME};
			Cursor cur = arg0[0].query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,prj, null, null, Phone.DISPLAY_NAME + " ASC");
			while(cur.moveToNext()){
				String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (!checkNames(temp,name)){
					temp.add(name);
					contacts.add(name);	
				}

			}
			cur.close();

			adp = new ContactAdapter(ctx, R.layout.list_item,contacts,arg0[0]);
			ContactActivity.listContact= contacts;
		}else {
			adp = new ContactAdapter(ctx, R.layout.list_item,lst,null);
			ContactActivity.listContact= lst;


		}
		return adp;
	}


	private void init() {
		contacts.add("Inserisci Numero");
	}

	private boolean checkNames(ArrayList<String> temp,String name) {
		if (temp.contains(name)){
			return true;
		}
		return false;
	}

	//	@Override
	//    protected void onPreExecute() {
	//        super.onPreExecute();
	//        ContactActivity.dialog = new ProgressDialog(ctx);
	//        ContactActivity.dialog.setMessage("Loading..");
	//        ContactActivity.dialog.setCancelable(true);
	//        ContactActivity.dialog.show();
	//    }
	//
	//	@Override
	//	protected void onPostExecute(Void r) {
	//        // dismiss the dialog once got all details
	//	    super.onPostExecute(r);
	//	    ContactActivity.dialog.dismiss();
	//		}
	//	
}
